package main

import (
	"context"
	"feishu-alter/config"
	"feishu-alter/global"
	"feishu-alter/router"
	"flag"
	"log"
	"net/http"
	"os"
	"os/signal"
	"time"

	"github.com/gin-gonic/gin"
)

func init() {
	var c config.Config
	var webhook, grafanaUrl, prometheusUrl string
	flag.StringVar(&webhook, "w", "", "指定 webhook 地址")
	flag.StringVar(&grafanaUrl, "g", "", "指定 grafana 地址")
	flag.StringVar(&prometheusUrl, "p", "", "指定 prometheus 地址")
	flag.Parse()
	if webhook == "" {
		webhook := os.Getenv("WEB_HOOK_URL")
		if webhook == "" {
			log.Fatalf("缺少WEB_HOOK_URL配置\n")
		}
		c.WebhookUrl = webhook
	}

	if grafanaUrl == "" {
		grafanaUrl := os.Getenv("GRAFANA_URL")
		if grafanaUrl == "" {
			log.Fatalf("缺少GRAFANA_URL配置\n")
		}
		c.GrafanaUrl = grafanaUrl
	}

	if prometheusUrl == "" {
		prometheusUrl := os.Getenv("PROMETHEUS_URL")
		if prometheusUrl == "" {
			log.Fatalf("缺少PROMETHEUS_URL配置\n")
		}
		c.PrometheusUrl = prometheusUrl
	}
	global.Config = &c
}

func main() {
	//gin.SetMode(gin.ReleaseMode)
	r := gin.Default()
	router.Router(r)
	s := &http.Server{
		Addr:           ":80",
		Handler:        r,
		ReadTimeout:    10 * time.Second,
		WriteTimeout:   10 * time.Second,
		MaxHeaderBytes: 1 << 20,
	}

	// 启动服务
	go func() {
		// 服务连接
		if err := s.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			log.Fatalf("listen: %s\n", err)
		}
	}()

	// 等待中断信号以优雅地关闭服务器（设置 10 秒的超时时间）
	quit := make(chan os.Signal)
	signal.Notify(quit, os.Interrupt)
	<-quit
	log.Println("服务10s后停止...")
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := s.Shutdown(ctx); err != nil {
		log.Fatal("服务停止失败:", err)
	}
	log.Println("服务已停止")
}
